import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  Logger,
} from '@nestjs/common';
import { Response } from 'express';
import { ApiResponse } from 'src/common/reponse.interface';
// 捕获 HTTP 异常
@Catch(HttpException)
// 实现 ExceptionFilter 接口
export class HttpFilterFilter implements ExceptionFilter {
  // 使用 NestJS 的 Logger 记录日志
  private readonly logger = new Logger(HttpFilterFilter.name);
  catch(exception: HttpException, host: ArgumentsHost) {
    // 获取 HTTP 上下文
    const ctx = host.switchToHttp();
    // 获取 HTTP 响应对象
    const response = ctx.getResponse<Response>();
    // 获取 HTTP 状态码
    const status = exception.getStatus();
    // 获取 HTTP 错误消息
    const message =
      exception instanceof HttpException ? exception.getResponse() : exception;

    this.logger.error(
      `HTTP Status: ${status} Error Message: ${JSON.stringify(message)}`,
    );
    // 构建错误响应对象
    const errorResponse: ApiResponse<any> = {
      statusCode: status,
      message: (message as any).message || 'Internal server error',
      data: null,
    };
    // 发送错误响应
    response.status(status).json(errorResponse);
  }
}
